import React, { useState, useEffect } from 'react'
import { Link, useHistory } from 'react-router-dom'
import { Form, Input, Button, Checkbox, message } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { userLogin } from '@/api/user'
import { setMyInfo } from '@/stores/user'
import { loginParams } from '@/types/user'
import './index.scss'

const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const { userInfo } = useSelector((state:any) => state.user)
  const [rememberMe, setRemember] = useState(false)

  useEffect(() => {
    if (userInfo) {
      history.go(-1)
      message.info('无需重复登录')
    }
  }, [])

  const onclickLogin = async(data: loginParams) => {
    try {
      const res = await userLogin(data)

      localStorage.setItem('token', res.data.token)
      dispatch(setMyInfo(res.data))
      history.push('/')
      message.success('登录成功')
    } catch (err) {
      console.log(err)
    }
  }

  return (
    <div className="login">
      <Form
        autoComplete="off"
        labelAlign="left"
        labelCol={{ span: 6 }}
        onFinish={onclickLogin}
      >
        <Form.Item
          label="邮箱"
          name="email"
          rules={[{ required: true, message: '请输入你的邮箱地址' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item className="controller">
          <Link
            className="item"
            to={'/change-password'}
          >
              修改密码
          </Link>
          <Link
            className="item"
            to={'/register'}
          >
              注册账号
          </Link>
          <Checkbox
            checked={rememberMe}
            className="item"
            onChange={(e) => setRemember(e.target.value)}
          >
              记住账号
          </Checkbox>
        </Form.Item>
        <Form.Item>
          <Button
            className="login-btn"
            htmlType="submit"
            type="primary"
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
